import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import Users from '../components/User/User.vue'
import Rights from '../components/Power/Rights.vue'
import Roles from '../components/Power/Roles.vue'
import Params from '../components/Goods/Params.vue'
import Category from '../components/Goods/Category.vue'
import Goods from '../components/Goods/Goods.vue'
import Addgood from '../components/Goods/Addgood.vue'
import Reports from '../components/Reports/Reports.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/params', component: Params },
      { path: '/categories', component: Category },
      { path: '/goods', component: Goods },
      { path: '/addgood', component: Addgood },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
// 路由守卫
router.beforeEach((to, from, next) => {
  // 如果是去登录页面可以直接去
  if (to.path === '/login') next()
  // 否则需要判断
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // 最后就是有token 可以直接放行
  next()
})

export default router
